package com.copm.demonstrationsystem.service.introductionfeatures.impl;

import com.copm.demonstrationsystem.commons.response.ResponseStatus;
import com.copm.demonstrationsystem.commons.util.ImageUtils;
import com.copm.demonstrationsystem.config.SystemConfig;
import com.copm.demonstrationsystem.dao.commons.ImageDao;
import com.copm.demonstrationsystem.dao.introductionfeatures.CompanyDevelopHistoryDao;
import com.copm.demonstrationsystem.pojo.commons.Image;
import com.copm.demonstrationsystem.pojo.introductionfeatures.CompanyDevelopHistory;
import com.copm.demonstrationsystem.service.introductionfeatures.CompanyDevelopHistoryService;
import com.copm.demonstrationsystem.service.introductionfeatures.commons.SinglonImageHandle;
import com.copm.demonstrationsystem.service.introductionfeatures.commons.TransformImagePath;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

import static java.lang.Math.floor;
import static java.lang.Math.log;

/**
 * @Author: Yuan Baiyu
 * @Date: Created in 23:54 2018/4/24
 */
@Service
public class CompanyDevelopHistoryServiceImpl implements CompanyDevelopHistoryService {

    private static Logger logger = LoggerFactory.getLogger(CompanyIntroductionServiceImpl.class);

    @Autowired
    private SystemConfig config;

    @Autowired
    CompanyDevelopHistoryDao companyDevelopHistoryDao;

    @Autowired
    SinglonImageHandle singlonImageHandle;

    @Autowired
    TransformImagePath transformImagePath;

    @Autowired
    ImageDao imageDao;

    private Object lock = new Object();

    @Override
    public ResponseStatus getPage() {
        ResponseStatus status = new ResponseStatus();
        //查询所有的“公司发展”页面信息
        List<CompanyDevelopHistory> pages = companyDevelopHistoryDao.findAll();
        //设置随机数，用于开始时间为null的页面默认值
        Long randomBeginTime = new Double(floor(Math.random() * 10000)).longValue();
        //以TreeMap将页面以开始日期排序
        Map<Long, CompanyDevelopHistory> treeMap = new TreeMap<Long, CompanyDevelopHistory>();
        //遍历存放页面对象
        for (int i = 0; i < pages.size(); i++) {
            CompanyDevelopHistory companyDevelopHistory = pages.get(i);
            if (null == companyDevelopHistory) {
                continue;
            }
            Long tempTime = pages.get(i).getBegin();
            Image image = companyDevelopHistory.getImage();
            if (null == image) {
                if (null == tempTime) {
                    status.setMessage("id为 " + pages.get(i).getId() + " 页面无开始日期，无法排序，请先添加！");
                    treeMap.put(randomBeginTime, companyDevelopHistory);
                } else {
                    treeMap.put(tempTime, companyDevelopHistory);
                }
                continue;
            }
            if (null == tempTime) {
                status.setMessage(pages.get(i) + "页面无开始日期，无法排序，请先添加！");
                image = transformImagePath.transformImagePath(image);
                treeMap.put(randomBeginTime, companyDevelopHistory);
                continue;
            }
            transformImagePath.transformImagePath(image);
            treeMap.put(tempTime, companyDevelopHistory);
        }
        //存放已排序的页面对象
        List<CompanyDevelopHistory> tree = new ArrayList<>(pages.size());
        Set<Long> keySet = treeMap.keySet();
        // 遍历 key 集合，获取 value
        for (Long key : keySet) {
            tree.add(treeMap.get(key));
        }

        if (0 != tree.size() && null != tree.get(0).getBackgroundImage()) {
            for (CompanyDevelopHistory com : tree) {
                Image backgroundImage = com.getBackgroundImage();
                if (null == backgroundImage) {
                    continue;
                } else {
                    backgroundImage = transformImagePath.transformImagePath(backgroundImage);
                }
            }
        }

        status.setStatue(1);
        status.setData(tree);

        logger.info("发展历程 页面信息查询成功！");
        return status;
    }

    @Override
    public ResponseStatus deleteCompanyDevelopHistoryImage(Long id) {
        ResponseStatus status;
        //获取页面对象
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        //获取图片名
        Image image = companyDevelopHistory.getImage();
        status = singlonImageHandle.deleteImage(image);
        if (status.getStatue() == 0) {
            return status;
        }
        //临时保存图片ID
        Long tempId = image.getId();
        //获取“发展历程”页面 ，设置图片为空
        companyDevelopHistory.setImage(null);
        //保存已删除的页面对象
        companyDevelopHistoryDao.save(companyDevelopHistory);
        //从图片对象中删除页面所对应的图片数据
        imageDao.delete(tempId);

        status.setStatue(1);
        logger.info("发展历程 id为 {} 的页面图片删除成功！", companyDevelopHistory.getId());
        return status;
    }


    @Override
    public ResponseStatus addCompanyDevelopHistoryImage(Long id, MultipartFile file) {
        ResponseStatus status = singlonImageHandle.storeAndCheckImage(file);
        if (status.getStatue() == 0) {
            return status;
        }
        //获取图片存储信息
        String[] paths = (String[]) status.getData();
        Image image = new Image(paths[0], paths[1], paths[2]);
        //获取“发展历程”页面对象
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        if (null == companyDevelopHistory) {
            //新建“发展历程”页面对象
            synchronized (lock) {
                companyDevelopHistory = companyDevelopHistoryDao.findOne((Long) addCompanyDevelopHistory().getData());
                companyDevelopHistoryDao.save(companyDevelopHistory);
            }
        }
        //设置“发展历程”页面图片
        companyDevelopHistory.setImage(image);
        //保存添加了图片的对象
        companyDevelopHistoryDao.save(companyDevelopHistory);
        status.setStatue(1);
        status.setData(companyDevelopHistory.getId());
        logger.info("发展历程 id为 {} 的页面图片添加成功！", companyDevelopHistory.getId());
        return status;
    }

    @Override
    public ResponseStatus modifyCompanyDevelopHistoryTitle(Long id, String title) {
        ResponseStatus status = new ResponseStatus();
        //查询“”页面（只有一个页面数据）
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        if (null == companyDevelopHistory) {
            synchronized (lock) {
                //新建“发展历程”页面对象
                companyDevelopHistory = companyDevelopHistoryDao.findOne((Long) addCompanyDevelopHistory().getData());
                companyDevelopHistoryDao.save(companyDevelopHistory);
            }
        }
        //设置页面对象
        companyDevelopHistory.setTitle(title);
        //保存页面对象
        companyDevelopHistoryDao.save(companyDevelopHistory);
        status.setStatue(1);
        status.setData(companyDevelopHistory.getId());
        logger.info("发展历程 id为 {} 的页面标题文本修改成功！", companyDevelopHistory.getId());
        return status;
    }

    @Override
    public ResponseStatus modifyCompanyDevelopHistoryContent(Long id, String content) {
        ResponseStatus status = new ResponseStatus();
        //查询“”页面（只有一个页面数据）
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        if (null == companyDevelopHistory) {
            synchronized (lock) {
                //新建“发展历程”页面对象
                companyDevelopHistory = companyDevelopHistoryDao.findOne((Long) addCompanyDevelopHistory().getData());
                companyDevelopHistoryDao.save(companyDevelopHistory);
            }
        }
        //设置页面对象
        companyDevelopHistory.setContent(content);
        //保存页面对象
        companyDevelopHistoryDao.save(companyDevelopHistory);
        status.setStatue(1);
        status.setData(companyDevelopHistory.getId());
        logger.info("发展历程 id为 {} 的页面文本内容修改成功！", companyDevelopHistory.getId());
        return status;
    }

    @Override
    public ResponseStatus modifyCompanyDevelopHistoryImage(Long id, MultipartFile file) {
        ResponseStatus status;
        //查找页面
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        if (null == companyDevelopHistory) {
            synchronized (lock) {
                //新建“发展历程”页面对象
                companyDevelopHistory = companyDevelopHistoryDao.findOne((Long) addCompanyDevelopHistory().getData());
                companyDevelopHistoryDao.save(companyDevelopHistory);
            }
        }
        if (null != companyDevelopHistory.getImage()) {
            status = deleteCompanyDevelopHistoryImage(id);
            if (status.getStatue() == 0) {
                return status;
            }
        }
        //添加图片
        status = addCompanyDevelopHistoryImage(companyDevelopHistory.getId(), file);
        status.setData(companyDevelopHistory.getId());
        logger.info("发展历程 id为 {} 的页面图片修改成功！", companyDevelopHistory.getId());
        return status;
    }

    @Override
    public ResponseStatus addCompanyDevelopHistoryBackgroundImage(MultipartFile file) {
        ResponseStatus status = singlonImageHandle.storeAndCheckImage(file);
        if (status.getStatue() == 0) {
            return status;
        }
        //获取图片存储信息
        String[] paths = (String[]) status.getData();
        Image image;
        //获取“发展历程”页面对象
        List<CompanyDevelopHistory> companyDevelopHistorys = companyDevelopHistoryDao.findPage();
        for (CompanyDevelopHistory c : companyDevelopHistorys) {
            image = new Image(paths[0], paths[1], paths[2]);
            //设置“发展历程”页面图片
            c.setBackgroundImage(image);
            companyDevelopHistoryDao.save(c);
        }
        status.setStatue(1);
        logger.info("发展历程 页面背景图片添加成功！");
        return status;
    }

    @Override
    public ResponseStatus deleteCompanyDevelopHistoryBackgroundImage(CompanyDevelopHistory c) {
        ResponseStatus status = new ResponseStatus();
        status.setStatue(1);
        //获取“发展历程”页面对象
        Image image;
        //获取图片名
        image = c.getBackgroundImage();
        status = singlonImageHandle.deleteImage(image);
        if (status.getStatue() == 0) {
            return status;
        }
        //临时保存图片ID
        Long tempId = image.getId();
        //设置图片为空
        c.setBackgroundImage(null);
        //保存已删除的页面对象
        companyDevelopHistoryDao.save(c);
        //从图片对象中删除页面所对应的图片数据
        imageDao.delete(tempId);
        status.setStatue(1);

        logger.info("发展历程 页面背景图片删除成功！");
        return status;
    }

    @Override
    public ResponseStatus modifyCompanyDevelopHistoryBackgroundImage(MultipartFile file) {
        ResponseStatus status;
        //获取“发展历程”页面对象
        List<CompanyDevelopHistory> companyDevelopHistorys = companyDevelopHistoryDao.findPage();
        //对象判空
        for (CompanyDevelopHistory c : companyDevelopHistorys) {
            if (null != c.getBackgroundImage()) {
                status = deleteCompanyDevelopHistoryBackgroundImage(c);
                if (status.getStatue() == 0) {
                    return status;
                }
            }
        }
        //添加图片
        status = addCompanyDevelopHistoryBackgroundImage(file);
        logger.info("发展历程 页面背景图片修改成功！");
        return status;
    }

    @Override
    public ResponseStatus deleteCompanyDevelopHistory(Long id) {
        ResponseStatus status = new ResponseStatus();
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        if (null == companyDevelopHistory) {
            status.setStatue(0);
            status.setMessage("无此id对应页面，请检查id");
            return status;
        }
        Image backgroundImage = companyDevelopHistory.getBackgroundImage();
        companyDevelopHistoryDao.delete(id);
        status = singlonImageHandle.deleteImage(backgroundImage);
        if (status.getStatue() == 0) {
            return status;
        }
        if (null != imageDao.findOne(backgroundImage.getId())) {
            imageDao.delete(backgroundImage);
        }
        status.setStatue(1);
        status.setData(companyDevelopHistory.getId());
        logger.info("发展历程 id为 {} 的页面删除成功！", companyDevelopHistory.getId());
        return status;
    }

    //添加一个页面
    @Override
    public ResponseStatus addCompanyDevelopHistory() {
        ResponseStatus status = new ResponseStatus();
        CompanyDevelopHistory companyDevelopHistory;
        //如果无“发展历程”页面，创建一张ID为1的页面
//        if (0 == companyDevelopHistoryDao.findAll().size()) {
//            companyDevelopHistory = new CompanyDevelopHistory(1L);
//        } else {
//            //查找已有页面的最大页面ID值
//            Long id = companyDevelopHistoryDao.findMaxId();
//            //根据Max(id)+Number 创建指定ID页面
//            if (null != companyDevelopHistoryDao.findOne(id + 1L)) {
//                companyDevelopHistory = new CompanyDevelopHistory(id + 13L);
//            } else {
//                companyDevelopHistory = new CompanyDevelopHistory(id + 1L);
//            }
//        }

        List<CompanyDevelopHistory> com = companyDevelopHistoryDao.findByBeginNull();
        for (CompanyDevelopHistory c : com) {
            if (null != c) {
                companyDevelopHistoryDao.delete(com);
                status.setMessage(c.getId() + " " + status.getMessage());
            }
        }
        synchronized (lock) {
            //新建“发展历程”页面对象
            companyDevelopHistory = new CompanyDevelopHistory("待填标签", "请输入文本", null, null, 2222L, 3333L);
            List<CompanyDevelopHistory> list = companyDevelopHistoryDao.findAll();
            if (list.size() != 0) {
                //背景图片只有一张，新建页面即复制已有页面对象的名字创建新对象
                String fileName = list.get(0).getBackgroundImage().getFileName();
                Image backgroundImage = new Image(fileName);
                companyDevelopHistory.setBackgroundImage(backgroundImage);
            }
            companyDevelopHistoryDao.save(companyDevelopHistory);
            status.setData(companyDevelopHistory.getId());
        }
        status.setStatue(1);
        logger.info("成功创建一个id为：" + companyDevelopHistory.getId() + "的页面！");
        return status;
    }

    @Override
    public ResponseStatus modifyCompanyDevelopHistoryBeginTime(Long id, Long begin) {
        ResponseStatus status = new ResponseStatus();
//        //修改开始时间时先查询，如果原有页面有一样的时间，删除页面
//        List<CompanyDevelopHistory> com = companyDevelopHistoryDao.findByBegin(begin);
//        for (CompanyDevelopHistory c : com) {
//            if (null != c) {
//                companyDevelopHistoryDao.delete(c);
//            }
//        }
        //查询“发展历程”页面（只有一个页面数据）
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        if (null == companyDevelopHistory) {
            synchronized (lock) {
                //新建“发展历程”页面对象
                companyDevelopHistory = companyDevelopHistoryDao.findOne((Long) addCompanyDevelopHistory().getData());
                companyDevelopHistoryDao.save(companyDevelopHistory);
            }
        }
        //设置页面对象
        companyDevelopHistory.setBegin(begin);
        //保存页面对象
        companyDevelopHistoryDao.save(companyDevelopHistory);
        status.setStatue(1);
        status.setData(companyDevelopHistory.getId());
        logger.info("发展历程 id为 {} 的页面开始时间修改成功！", companyDevelopHistory.getId());
        return status;
    }

    @Override
    public ResponseStatus modifyCompanyDevelopHistoryEndTime(Long id, Long end) {
        ResponseStatus status = new ResponseStatus();
        //查询“”页面（只有一个页面数据）
        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
        if (null == companyDevelopHistory) {
            synchronized (lock) {
                //新建“发展历程”页面对象
                companyDevelopHistory = companyDevelopHistoryDao.findOne((Long) addCompanyDevelopHistory().getData());
                companyDevelopHistoryDao.save(companyDevelopHistory);
            }
        }
        //设置页面对象
        companyDevelopHistory.setEnd(end);
        //保存页面对象
        companyDevelopHistoryDao.save(companyDevelopHistory);
        status.setStatue(1);
        status.setData(companyDevelopHistory.getId());
        logger.info("发展历程 id为 {} 的页面结束时间修改成功！", companyDevelopHistory.getId());
        return status;
    }


    //    @Override
//    public ResponseStatus addCompanyDevelopHistoryBeginTime(Long id, Long begin) {
//        ResponseStatus status = new ResponseStatus();
//        //根据传入ID判断是否存在此页面，存在即在此添加，不存在就创建新页面
//        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
//        if (null == companyDevelopHistory) {
//            //创建新页面
//            companyDevelopHistory = new CompanyDevelopHistory(id);
//        }
//        //设置开始日期
//        companyDevelopHistory.setBegin(begin);
//        companyDevelopHistoryDao.save(companyDevelopHistory);
//        status.setStatue(1);
//        return status;
//    }
//
//    @Override
//    public ResponseStatus addCompanyDevelopHistoryEndTime(Long id, Long end) {
//        ResponseStatus status = new ResponseStatus();
//        //根据传入ID判断是否存在此页面，存在即在此添加，不存在就创建新页面
//        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
//        if (null == companyDevelopHistory) {
//            //创建新页面
//            companyDevelopHistory = new CompanyDevelopHistory(id);
//        }
//        //设置开始日期
//        companyDevelopHistory.setEnd(end);
//        companyDevelopHistoryDao.save(companyDevelopHistory);
//        status.setStatue(1);
//        return status;
//    }


//    @Override
//    public ResponseStatus deleteCompanyDevelopHistoryBeginTime(Long id) {
//        ResponseStatus status = new ResponseStatus();
//        //根据页面ID查找指定页面
//        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
//        //判断页面是否存在
//        if (null == companyDevelopHistory) {
//            status.setStatue(0);
//            status.setMessage("无法由ID查找到待删除的页面内容文本，请确认页面ID");
//            return status;
//        }
//        //设置页面开始日期为空（删除）
//        companyDevelopHistory.setBegin(null);
//        companyDevelopHistoryDao.save(companyDevelopHistory);
//        status.setStatue(1);
//        return status;
//    }
//
//    @Override
//    public ResponseStatus deleteCompanyDevelopHistoryEndTime(Long id) {
//        ResponseStatus status = new ResponseStatus();
//        //根据页面ID查找指定页面
//        CompanyDevelopHistory companyDevelopHistory = companyDevelopHistoryDao.findOne(id);
//        //判断页面是否存在
//        if (null == companyDevelopHistory) {
//            status.setStatue(0);
//            status.setMessage("无法由ID查找到待删除的页面内容文本，请确认页面ID");
//            return status;
//        }
//        //设置页面截止日期为空（删除）
//        companyDevelopHistory.setEnd(null);
//        companyDevelopHistoryDao.save(companyDevelopHistory);
//        status.setStatue(1);
//        return status;
//    }

}
